<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="./dist/qrcode.js"></script>
  <script src="./dist/html2canvas.js"></script>
  <script src="./dist/jspdf.js"></script>
  <script src="./dist/moment.js"></script>
  <title>社保记录</title>
  <style>
    @media print {

      /* 设置横向打印 */
      /* 设置纵向打印 */
      @page {
        size: portrait;
      }
    }

    body {
      display: flex;
      flex-wrap: wrap;
      flex-shrink: inherit;
      flex-direction: column;
      font-family: 'Arial', sans-serif;
      margin: 0 auto;
      padding: 0;
      background-color: #fff;
    }

    .box {
      margin: 0px auto;
      padding: 12px;
      width: 972px;
      background-color: #fff;
    }

    .title {
      position: relative;
      text-align: center;
      font-size: 26px;
      margin: 46px 0 24px;
    }

    .title .qr {
      position: absolute;
      left: 12px;
      top: -42px;
      font-size: 22px;
      width: 98px;
      height: 100px;
      background: center / 100% no-repeat;
    }

    table {
      border-collapse: collapse;
      width: 90%;
      margin-top: 20px;
    }

    th,
    td {
      border: 1px solid #000;
      padding: 12px 2px 12px 2px;
      font-size: 14px;
      text-align: center;
    }

    td p {
      text-align: start;
      padding-left: 18px;
      margin: 2px 0;
    }

    th {
      background-color: #f2f2f2;
    }

    .table1 {
      border-collapse: collapse;
      margin-top: 20px;
      width: 90%;
    }

    .table1 td {
      border: 1px solid #000;
      padding: 12px;
      font-size: 14px;
      text-align: center;
    }

    .tips {
      font-size: 12px;
      color: #5d5d5d;
      padding-left: 12px;
    }

    .Insured-status,
    .payment-num {
      white-space: nowrap;
    }

    .bottom-tr td {
      height: 40px;
    }

    .bottom {
      display: flex;
      position: relative;
      width: 962px;
      justify-content: space-between;
      align-items: center;
      margin-top: 8px;
    }

    .bottom .print-time {
      margin-left: 32px;
    }

    .bottom .zhang {
      position: absolute;
      top: -100px;
      left: 69%;
      width: 204px;
      height: 204px;
      background: url(./dist/sb.png) center no-repeat;
      opacity: 0.6;
    }

    #exportButton {
      margin: 10px;
      padding: 8px 16px;
      background-color: #007bff;
      color: #fff;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      position: absolute;
      top: 24px;
      right: 24px;
    }

    #exportButton:hover {
      background-color: #0056b3;
    }
  </style>
</head>

<body>
  <div class="box" id="content">
    <div class="tips" id="tips">扫描二维码或访问云南人社表单验证系统<span class="tips-url">https://</span>验证真伪，验证号码<span
        class="tips-code"></span>
    </div>
    <div class="title">云南省城镇职工基本养老保险个人参保证明 <div class="qr" id="qrcode"></div>
    </div>
    <table class="table1">
      <tr>
        <td colspan="1.5">姓名</td>
        <td colspan="1.5" class="user-name"></td>
        <td colspan="2">性别</td>
        <td colspan="1" class="user-gender"></td>
        <td>个人编号</td>
        <td class="user-code"></td>
        <td colspan="2">身份证号</td>
        <td colspan="3" class="user-idcardnumber"></td>
      </tr>
      <tr>
        <td>当前参保缴费状态</td>
        <td class="Insured-status"></td>
        <td colspan="2">实际缴费月数</td>
        <td colspan="1" class="payment-num"></td>
        <td style="padding-left: 1px;padding-right: 1px;">现参保单位</td>
        <td colspan="6" class="Insured-entity-up"></td>
      </tr>
      <tr>
        <td rowspan="2" colspan="1.5">个人参保缴费情况</td>
        <td colspan="3">参保时间起止日期</td>
        <td colspan="2">参保单位</td>
        <td colspan="3">经办机构</td>
        <td colspan="3">险种</td>
      </tr>
      <tr>
        <!-- 参保时间 -->
        <td colspan="3" class="time-enrollment"></td>
        <!-- 参保单位 -->
        <td colspan="2" class="Insured-entity-btm"></td>
        <!-- 经办机构 -->
        <td colspan="3" class="handling-agency"></td>
        <!-- 险种 -->
        <td colspan="3" class="insurance-type"></td>
      </tr>
      <tr>
        <td colspan="12" style="height: 22px;"></td>
      </tr>
      <tr style="white-space: nowrap;font-weight: 600;" c>
        <td>缴费年份</td>
        <td>缴费月份</td>
        <td>缴费基数</td>
        <td>单位缴纳</td>
        <td>个人缴纳</td>
        <td>缴费状态</td>
        <td>缴费年份</td>
        <td>缴费月份</td>
        <td>缴费基数</td>
        <td>单位缴纳</td>
        <td>个人缴纳</td>
        <td>缴费状态</td>
      </tr>
      <tbody id="bottom-tr" style="font-size: 14px;"></tbody>
    </table>
    <div class="bottom">
      <span>制表人:<span class="lister"></span></span>
      <span>打印日期：<span class="print-time"></span></span>
      <div class="bottom zhang"></div>

    </div>
  </div>
  <!-- Export button -->
  <button id="exportButton">导出</button>
  <!-- Scripts -->
  <script>

  </script>
  <script>
    var queryString = window.location.search
    var urlParams = new URLSearchParams(queryString)
    var id = urlParams.get('id')
    function generateRandomCode(length) {
      const charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
      let code = ''

      for (let i = 0; i < length; i++) {
        const randomIndex = Math.floor(Math.random() * charset.length)
        code += charset[randomIndex]
      }

      return code
    }
    const code_v = generateRandomCode(32)
    // 上面表格数据
    var info = {
      name: "白梅", // 姓名
      gender: "女", // 性别
      personalNumber: "53010314144420", // 个人编号
      idCardNumber: "530427199307280921", // 身份证号
      insuranceStatus: "正常参保", // 当前参保缴费状态
      paidMonths: "31", // 实际缴费月数
      currentInsuranceUnit: "云南北极光数码科技有限公司", // 现参保单位
      insurancePeriod: "2021年03月至一", // 参保时间起止日期
      insuranceUnit: "云南北极光数码科技有限公司", // 参保单位
      handlingAgency: "昆明市盘龙区社会保险局", // 经办机构
      insuranceType: "城镇职工基本养老保险",   // 险种
      tips_url: 'https://hrss.yn.gov.cn/zwfw/form/', // 顶部验证系统链接
      tips_code: '', // 验证号码
      lister: '云南人社服务网上大厅(单位服务)',// 制表人
      print_time: '2023年10月10日',// 打印时间

    }
    // 用于动态填充用户信息的函数
    function fillUserInfo() {
      document.querySelector('.tips-url').innerText = info.tips_url || 'https://hrssyn gov.cn /zwfw/form'
      document.querySelector('.tips-code').innerText = info.tips_code.toLocaleLowerCase()
      document.querySelector('.user-name').innerText = info.name
      document.querySelector('.user-gender').innerText = info.gender
      document.querySelector('.user-code').innerText = info.personalNumber
      document.querySelector('.user-idcardnumber').innerText = info.idCardNumber
      document.querySelector('.Insured-status').innerText = info.insuranceStatus
      document.querySelector('.payment-num').innerText = info.paidMonths
      document.querySelector('.Insured-entity-up').innerText = info.currentInsuranceUnit
      document.querySelector('.time-enrollment').innerText = info.insurancePeriod
      document.querySelector('.Insured-entity-btm').innerText = info.insuranceUnit
      document.querySelector('.handling-agency').innerText = info.handlingAgency
      document.querySelector('.insurance-type').innerText = info.insuranceType
      document.querySelector('.lister').innerText = info.lister || '云南人社服务网上大厅（单位服务）'
      // 创建一个 Date 对象，表示当前时间
      const currentDate = new Date()

      // 获取年、月、日
      const year = currentDate.getFullYear()
      const month = String(currentDate.getMonth() + 1).padStart(2, '0') // 月份是从 0 开始的，因此要加 1
      const day = String(currentDate.getDate()).padStart(2, '0')
      // 构建格式化的日期字符串（例如：2023-11-13）
      const formattedDate = `${year}年${month}月${day}日`
      document.querySelector('.print-time').innerText = info.print_time || formattedDate
    }

    // 下面表格数据
    var paymentData = [
      { paymentYear: 2022, paymentMonth: 1, paymentBase: 5000, companyPayment: 1000, personalPayment: 500, paymentStatus: "正常", paymentYear2: 2022, paymentMonth2: 1, paymentBase2: 5000, companyPayment2: 1000, personalPayment2: 500, paymentStatus2: "正常" },
      // 添加更多数据
    ]
    // 用于动态填充缴费情况表格的函数
    function fillPaymentTable() {
      var paymentTable = document.querySelector('.box table')
      var paymentBody = document.querySelector('#bottom-tr')
      // 清空表格内容
      paymentBody.innerHTML = ''
      // 遍历数据，动态生成表格行
      paymentData.forEach(function (payment) {
        var row = document.createElement('tr')
        row.innerHTML = `
          <td>${payment.paymentYear}</td>
          <td>${Number(payment.paymentMonth || 0) < 10 ? `0${payment.paymentMonth}` : payment.paymentMonth}</td>
          <td>${payment.paymentBase}</td>
          <td>${payment.companyPayment}</td>
          <td>${payment.personalPayment}</td>
          <td>${payment.paymentStatus}</td>
          <td>${payment.paymentYear2 || ''}</td>
          <td>${Number(payment.paymentMonth2 || 0) < 10 ? `0${payment.paymentMonth2}` : payment.paymentMonth2}</td>
          <td>${payment.paymentBase2 || '0'}</td>
          <td>${payment.companyPayment2 || '0'}</td>
          <td>${payment.personalPayment2 || '0'}</td>
          <td>${payment.paymentStatus2 || ''}</td>
        `
        paymentBody.appendChild(row)
      })
      var shuoming = `
        <tr>
          <td colspan="2">说明</td>
          <td colspan="10">
            <p>1、本证明由参保人员持本人身份证原件开具；</p>
            <p>2、本证明仅为参保人员基本养老保险的情况记录，不具有任何担保作用；</p>
            <p>3、本证明不适用于养老保险关系转移。</p>
          </td>
        </tr>`
      paymentBody.insertAdjacentHTML('beforeend', shuoming)
      paymentTable.appendChild(paymentBody)
    }
    // 获取当前页面的 URL
    var currentURL = `http://sys.ynjov.com/socialres.html?id=${id}&code=${code_v}` // 二维码

    // 创建 QRCode 实例并将二维码添加到页面
    var qrcode = new QRCode(document.getElementById("qrcode"), {
      text: currentURL,
      width: 98,
      height: 98
    })
    // 页面加载时调用填充表格数据的函数
    // 页面加载时调用填充用户信息和表格数据的函数
    window.onload = function () {
      if (urlParams.get('isMobile')) {
        document.getElementById("exportButton").hidden = true
        document.getElementById("tips").hidden = true
      }
      fetch(`http://api.ynjov.com:8080/api/getInsuredPersonDetail/${id}?insuredPersonId=${id}`)
        .then(response => {
          if (!response.ok) {
            throw new Error('Network response was not ok')
          }
          return response.json()
        })
        .then(({ data, items }) => {
          console.log(data)
          info = data
          info.tips_code = code_v
          excMonth(items || [])
          fillUserInfo()

        })
        .catch(error => {
          console.error('Fetch error:', error)
        })
    }
    function excMonth(data) {
      let dt = data.map(item => {
        return { ...item, date: moment(item.paymentYear + '' + (Number(item.paymentMonth) < 10 ? `0${item.paymentMonth}` : item.paymentMonth) + '01').format('YYYYMMDD') }
      }).sort((a, b) => Number(a.date - b.date))
      const lencop = 24 - dt.length + 1
      if (dt.length < 24) {
        for (let i = 1; i < lencop; i++) {
          const date = moment(dt[0].date).add(-i, 'months').format('YYYYMMDD')
          dt.push({
            companyPayment: 0,
            date,
            paymentYear: moment(date).format('YYYY'),
            paymentMonth: moment(date).format('M'),
            paymentStatus: '',
            paymentBase: 0,
            personalPayment: 0,
          })
        }
      }
      if (dt.length > 24) {
        dt.splice(0, length - 24)
      }
      dt = dt.sort((a, b) => Number(a.date - b.date))
      // 按照年和月排序
      const sortedData = dt.sort((a, b) => {
        if (a.paymentYear === b.paymentYear) {
          return a.paymentMonth - b.paymentMonth
        }
        return a.paymentYear - b.paymentYear
      }).slice(-24)

      // 计算分组位置
      const midIndex = Math.ceil(sortedData.length / 2)

      // 分组
      let leftGroup, rightGroup
      if (sortedData.length % 2 === 0) {
        leftGroup = sortedData.slice(0, midIndex)
        rightGroup = sortedData.slice(midIndex)
      } else {
        leftGroup = sortedData.slice(0, midIndex + 1)
        rightGroup = sortedData.slice(midIndex + 1)
      }

      // 如果左边元素多于右边，则调整右边的分组
      if (leftGroup.length > rightGroup.length) {
        rightGroup.push(leftGroup.pop())
      }


      // 输出分组数据
      console.log('左边分组：', leftGroup)
      console.log('右边分组：', rightGroup)
      let arr = []
      leftGroup.forEach((item, index) => {
        if (rightGroup[index]) {
          const e = rightGroup[index]
          const rightItem = { paymentYear2: e.paymentYear, paymentMonth2: e.paymentMonth, paymentBase2: e.paymentBase, companyPayment2: e.companyPayment, personalPayment2: e.personalPayment, paymentStatus2: e.paymentStatus }
          arr.push({ ...item, ...rightItem })
        }
        else {
          arr.push({ ...item })
        }
      })
      paymentData = [...arr]
      fillPaymentTable(paymentData)
    }
    // 获取要导出的HTML元素
    const element = document.getElementById('content')

    const pdf = new jsPDF()
    // 使用 html2pdf 将 HTML 元素导出为 PDF
    exportButton.addEventListener('click', () => {
      document.getElementById("exportButton").hidden = true
      window.document.title = `${info.name}社保`
      window.print()
      document.getElementById("exportButton").hidden = false
      window.document.title = `社保记录`
    })
  </script>
</body>

</html>